import { IRouterContext } from "koa-router";
import { sql } from "../util/db";
import { getImgurl } from "../util/imge";
import { Sex } from "../enum";

export const findOneByOpenid = async (ctx: IRouterContext) => {
    const openid = ctx.params.openid;
    const text = `select * from t_user where openid=$1`
    const { rows } = await sql.query(text, [openid]);
    rows[0].headimgurl = getImgurl(rows[0].headimgurl);
    ctx.body = rows[0];
}

export const update = async (ctx: IRouterContext | any) => {
    const body = ctx.req.body || ctx.request.body;
    const openid = ctx.params.openid;
    const headimgurl = (ctx.req.file && ctx.req.file.filename) || null;
    if (headimgurl) {
        body.headimgurl = headimgurl;
    }
    let text = `update t_user set `;
    let count = 0;
    let params: string[] = [];
    for (let key of Object.keys(body)) {
        if (key === 'sex') {
            text += `${key}=\$${++count},`;
            params.push(Sex[body[key]]);
            continue;
        }
        text += `${key}=\$${++count},`;
        params.push(body[key]);
    }
    text = text.substring(0, text.length - 1);
    text += ` where openid=\$${++count}`;
    params.push(openid);
    const { rowCount } = await sql.query(text, params);
    ctx.body = rowCount;
}